const { createDfuseClient } = require("@dfuse/client")
const client = createDfuseClient({
  apiKey: "<Paste your API key here>",
  network: "mainnet.eos.dfuse.io",
})

global.fetch = require('node-fetch')
global.WebSocket = require('ws')

import nodeFetch from "node-fetch"
import WebSocketClient from "ws"

const streamTransfer = `subscription($cursor: String!) {
  searchTransactionsForward(query: "receiver:eosio.token action:transfer -data.quantity:'0.0001 EOS'", cursor: $cursor) {
    undo cursor
    trace {
      matchingActions { json }
    }
  }
}`

;(async ()=>{


await client.graphql(streamTransfer, (message, stream) => {
  if (message.type === "error") {
    console.log("An error occurred", message.errors, message.terminal)
  }

  if (message.type === "data") {
    const data = message.data.searchTransactionsForward
    const actions = data.trace.matchingActions

    actions.forEach(({ json }: any) => {
      const { from, to, quantity, memo } = json
      console.log(`Transfer [${from} -> ${to}, ${quantity}] (${memo})`)
    })

    stream.mark({ cursor: data.cursor })
  }

  if (message.type === "complete") {
    console.log("Stream completed")
  }
})

})()